<?php

    $rootDir = $_SERVER['DOCUMENT_ROOT'];

    require_once($rootDir.'/classes/SessionManager.class.php'); 
    require_once($rootDir.'/classes/db/SQLiteConnector.class.php');
    require_once($rootDir.'/classes/LeproUser.class.php');   
    require_once($rootDir.'/classes/db/LeproUserDAO.class.php');
    require_once($rootDir.'/classes/LeproHelper.class.php');
    require_once($rootDir.'/classes/Card.class.php');    
    
    class EResultConstants {
    
        const NO_ERRORS = 0;
        const PWD_ERROR = -1;
        const RPWD_ERROR = -2;
        const EMAIL_ERROR = -3;
        const CAPTCHA_ERROR = -4;
        const GUDATA_ERROR = -5;
        const PREP_ERROR = -6;
        const UID_ERROR = -7;
        const UDATA_ERROR = -8;
        const PWDMATCH_ERROR = -9;
        const PWDCMP_ERROR = -10;   
    
    }
    
    // TODO: turn this into class
    
    $sstr_re = "/^[A-Za-z0-9]*$/";
    $email_re = "/^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$/";
    // $email_re = "/^(.+)@([^\(\);:,<>]+\.[a-zA-Z]{2,4})$/";
    $captcha_re = "/^[A-Za-z]{6}$/";
    $lcode_re = "/^[A-Za-z0-9]{16}$/";   

    $password = urldecode($_POST['pwd']);
    $re_password = urldecode($_POST['re-pwd']);
    $email = urldecode($_POST['email']);
    $captcha = urldecode($_POST['captcha']);
    $logincode = urldecode($_POST['lcode']); 
    
    $result = EResultConstants::NO_ERRORS;
    
    if ((strlen($password) == 0) || !(preg_match($sstr_re, $password) > 0)) $result = EResultConstants::PWD_ERROR;
    if ((result == EResultConstants::NO_ERRORS) && SessionManager::isUserPrepared()) { // if password is in correct form and we have prepared user
        $userId = SessionManager::getPreparedUserId(); // get his id
        if ($userId != null) { // check, if it's ok
            settype($userId, 'integer'); 
            $isDirtyUser = LeproHelper::isDirtyUser($userId); // remember, if he is from dirty.ru
            $connector = SQLiteConnector::getInstance();
            if ($connector->connect()) { // connect to DB
                $userDAO = new LeproUserDAO($connector->getDB()); 
                $user = $userDAO->load($userId); // try to load this user from DB
                $isUserRegistered = ($user != null); // if we've got user - then he is registered
                if ($isUserRegistered) {
                    if (md5($user->getID().$user->getUsername().$password) == $user->getPwdHash()) {
                        SessionManager::loginUser($userId);
                    } else $result = EResultConstants::PWDMATCH_ERROR;
                } else {
                    if ((strlen($re_password) == 0) || !(preg_match($sstr_re,  $re_password) > 0)) $result = EResultConstants::RPWD_ERROR;
                    if ((strlen($email) > 0) && !(preg_match($email_re, $email) > 0)) $result = EResultConstants::EMAIL_ERROR;                    
                    if ($result == EResultConstants::NO_ERRORS) {
                        if (strcmp($password, $re_password) == 0) {
                            SessionManager::loginUser($userId);
                            SessionManager::setRegistrationRequired();
                        } else $result = EResultConstants::PWDCMP_ERROR;
                    }
                }
                if ($result == EResultConstants::NO_ERRORS) { // if everything is still ok
                    if (!$isDirtyUser && !LeproHelper::isLoggedIn()) { // if we are meeting leprosorium user - we need to login
                        if ((strlen($captcha) > 0) && (preg_match($captcha_re, $captcha) > 0) && 
                            (strlen($logincode) > 0) && (preg_match($lcode_re, $logincode) > 0)) {
                            LeproHelper::login($logincode, $captcha);
                        } else $result = EResultConstants::CAPTCHA_ERROR; 
                    }
                    // $userPage = LeproHelper::getUserPage($userId, $isDirtyUser); // try to get users' page
                    $userData = LeproHelper::getUserData($userId); // try to get users' data 
                    if ($userData != null) {
                        if ($userData != -1) {
                            if ($result == EResultConstants::NO_ERRORS) {
                                $cardId = $isUserRegistered ? $user->getCardID() : Card::getCardIdByUserData(
                                    $isDirtyUser ? $userData['voice'] : LeproUser::getVoice($userData['rating']),
                                    $userData['karma']);
                                $userData['card'] = Card::getCardSummary($cardId);                                 
                                $result = json_encode($userData);
                                if (!$isUserRegistered) {
                                    SessionManager::registerVar('pwdhash', md5($userId.$userData['userName'].$password));
                                    SessionManager::registerVar('email', $email);
                                    SessionManager::registerVar('cardId', $cardId);
                                    SessionManager::registerVar('uname', $userData['userName']);
                                    SessionManager::registerVar('time', time()); // $_SERVER['REQUEST_TIME']
                                }                                
                            }
                        } else if ($result == EResultConstants::NO_ERRORS) $result = EResultConstants::UDATA_ERROR;
                    } else if ($result == EResultConstants::NO_ERRORS) $result = EResultConstants::GUDATA_ERROR;                     
                }        
            } 
        } else $result = EResultConstants::UID_ERROR;
    } else if (result == EResultConstants::NO_ERRORS) $result = EResultConstants::PREP_ERROR;    
    
    if ($result != EResultConstants::NO_ERRORS) SessionManager::clearSessionData(array('pwdhash', 'email', 'cardId', 'uname', 'time'));  
     
    echo $result;

?>
